<!--
施工单位重新制定计划
-->
<template>
  <my-dialog @on-submit="submitHandle" :subLoading="subLoading">
    <my-header slot="header"
               project-sub-text="施工单位进度计划"  project-sub-title="施工单位上报"
               :project-name="projectDetail.project_name"  ></my-header>
    <div slot="body">
      <widgets title="标段名称" :value="projectDetail.sction_name" icon="section"></widgets>
      <widgets title="合同工期" :value="projectDetail.contract_time" icon="contract"></widgets>
      <widgets title="施工单位" :value="projectDetail.construction_organeation" icon="organization"></widgets>
      <widgets title="项目负责人" :value="projectDetail.project_manager" icon="responsibility"></widgets>
      <my-textarea label-text="进度调整原因" v-model="changeReason"></my-textarea>
      <div style="color:#777;width: 100%;display: block;height: 50px;float: left;clear: both;line-height: 50px;font-size: 20px;margin-bottom:15px;">施工单位进度图</div>
      <chart :read-only="readOnly" :project.sync="chartProjectData"></chart>
      <load @loadedFile="uploadSuccessHandle" @onDelete="deleteSuccessHandle"></load>
    </div>
  </my-dialog>
</template>

<script>
  import Dialog from "@/components/Dialog";
  import Header from "@/components/Dialog/Header";
  import Widgets from "@/components/Dialog/Widgets";
  import TextArea from "@/components/Dialog/TextArea";
  import Load from "@/components/Dialog/Load";
  import Chart from "@/components/Dialog/Chart";
  import CheckBox from "@/components/Dialog/Check";
  import _ from 'lodash'
  import { mapGetters } from 'vuex'

  export default{
    name: 'CscUnitReplan',
    data () {
      return {
        files: [],
        projectDetail: {

        },
        changeReason:"",
        readOnly:false,
        chartProjectData:[],
        subLoading:false,
        check_plan_id:""
      }
    },
    computed: {
      ...mapGetters([
        'userData'
      ])
    },
    created () {

      this.readOnly = this.$route.params.readonly;

      this.taskId=this.$route.params.taskId;

      this.projectId=this.$route.params.projectId;

      this.getProjectInfo();

      this.$store.dispatch('getProgressPlan',{
        'token':this.userData.token,
        'pId':this.projectId,
        'taskId':this.taskId
      }).then(res =>{

        if(res.statusText=="OK"&&res.status==200){

          const branch_project=res.data.branch_project;

          if (branch_project) {

            for(var i=0;i<branch_project.length;i++){

              var tempObj = {
                projectName:"",
                items:[]
              };

              var primary=branch_project[i];

              tempObj.projectName=primary.branch_project_name;

              for (var j=0;j<primary.branch_son_project.length;j++){

                var tempSubObj={
                  id:'',
                  subName:"",
                  startDate:'',
                  endDate:''
                };

                var secondary=primary.branch_son_project[j];

                tempSubObj.id=secondary.id;

                tempSubObj.subName=secondary.branch_son_project_name;
                tempSubObj.startDate=secondary.construction_begin_at;
                tempSubObj.endDate=secondary.construction_end_at;

                tempObj.items.push(tempSubObj);

              }

              this.chartProjectData.push(tempObj);

            }
          }
        }

      },res =>{

        this.$message('错误，请求数据失败,错误信息:'+JSON.stringify(res));

      }).catch(err =>{

        this.$message('系统错误，请求数据失败,错误信息:'+JSON.stringify(err));

      });

    },
    components: {
      'MyDialog': Dialog,
      'MyHeader': Header,
      Widgets,
      Load,
      'MyTextarea': TextArea,
      CheckBox,
      Chart
    },
    methods: {
      submitHandle () {

        this.subLoading = true;

        var self=this;

        var branch_project= this.getChartData();

        this.$store.dispatch('getTaskInfo',{
          token:this.userData.token,
          task_id:this.taskId
        }).then((res)=>{


          var check_plan_id=-1;

          if (res.status==200&&res.statusText=="OK"){

            check_plan_id=res.data.data.check_plan_id;

          }

          var file=[];

          this.projectDetail.file.forEach(item=>{
            file.push({id:item.id});
          });


          var target=[];

          for(var i=0;i<branch_project.length;i++){

           for(var j=0;j<branch_project[i].branch_son_project.length;j++){

             target.push({
               id:branch_project[i].branch_son_project[j].id,
               construction_begin_at:branch_project[i].branch_son_project[j].construction_begin_at,
               construction_end_at:branch_project[i].branch_son_project[j].construction_end_at
             });

           }

          }


          this.$store.dispatch('modifyBuildPlan',{
            token:this.userData.token,
            'task_id':this.taskId,
            'project_id':this.projectId,
            'users_id':this.userData.id,
            file,
            branch_son_project:target,
            "check_plan_id":check_plan_id,
            'cause':this.changeReason
          }).then(res => {

            if(res.status==200&&res.statusText=="OK"){

              this.$message('提交数据成功!');

              this.$router.go(-1);
            }
            else {

              this.$message('数据提交失败，错误信息：'+res.data);

            }

            self.subLoading = false;

          },res => {

            this.$message('数据提交失败，错误信息：'+JSON.stringify(res));

          }).catch(err => {

            this.$message('系统错误，提交信息失败，错误信息:'+JSON.stringify(err));

          });


        }).catch(err =>{

          console.log(err);

        })



      },
      getChartData(){

        var copyProject=JSON.parse(JSON.stringify(this.chartProjectData));

        var counter=copyProject.length-1;

        /**
         * 删除所有的未编辑的项目
         */
        while(true){

          if(copyProject[counter].projectName=='待编辑项目'){

            copyProject.splice(counter,1);

            counter=copyProject.length-1;
          }
          else {
            counter--;
          }

          if (counter<0){
            break;
          }
        }


        var output=[];

        for (var i=0;i<copyProject.length;i++){

          /**
           * {
            projectName:"项目6",
            items:[{
              subName:"子选项8",
              startDate:'2013-9-6',
              endDate:'2017-6-15'
            },{
              subName:'子选项9',
              startDate:'2016-2-28',
              endDate:'2016-3-28'
            }]
          }
           */

          var branch_project_item={
            "branch_project_name": "",
            "branch_son_project":[]
          };

          branch_project_item.branch_project_name=copyProject[i].projectName;

          for(var j=0;j<copyProject[i].items.length;j++){

            var branch_son_project_item={
              id:"",
              "branch_son_project_name": "",
              "construction_begin_at": "",
              "construction_end_at": ""
            }

            branch_son_project_item.branch_son_project_name=copyProject[i].items[j].subName;

            branch_son_project_item.id=copyProject[i].items[j].id;

            branch_son_project_item.construction_begin_at=copyProject[i].items[j].startDate;

            branch_son_project_item.construction_end_at=copyProject[i].items[j].endDate;

            branch_project_item.branch_son_project.push(branch_son_project_item);
          }

          output.push(branch_project_item);

        }

        return output;

      },
      getProjectInfo () {
        const projectId = this.$route.params.projectId

        this.$store.dispatch('getSingeProject', {token: this.userData.token, pId: projectId}).then(res => {

          this.projectDetail = res.data;

        }, (res) => {
          this.$message(`数据请求失败,错误信息:${JSON.stringify(res)}`)
        }).catch(err => {
          this.$message(`系统错误，请求数据错误，错误信息:${JSON.stringify(err)}`)
        })

      },
      uploadSuccessHandle ({data}) {
        this.files.push({id: data.id})
      },
      deleteSuccessHandle ({id}) {
        _.remove(this.files, o => {
          return o.id === id
        })
      }
    }
  }
</script>
